package com.example.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class NetUtils {

    private static final Logger logger = LoggerFactory.getLogger(NetUtils.class);

    public static String getClientIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip = null;

        if (realIp == null || realIp.trim().length() < 1) {
            if (forwarded == null || forwarded.trim().length() < 1) {
                ip = remoteAddr;
            } else {
                logger.debug("login ip forwarded: {0}", forwarded);
                ip = forwarded.split(",")[0];
            }
        } else {
            logger.debug("login ip realIp: {0}", realIp);
            if (forwarded != null && forwarded.trim().length() > 0) {
                logger.debug("login ip forwarded: {0}", forwarded);
                ip = forwarded.split(",")[0];
            } else {
                ip = realIp;
            }
        }
        return ip;
    }
}
